package com.aaa.utils;

import com.aaa.entity.User;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.JWTVerifier;
import lombok.extern.slf4j.Slf4j;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * -*- coding:utf-8 -*-
 *
 * @author 太阳偷渡青山
 * @software IntelliJ IDEA
 * @date 2022/11/23 10:04
 * @Description JwtUtil 设置token工具类
 */
@Slf4j
public class JwtUtil {

    private static final String SIGN = "aaa"; //密钥

    /**
     * 创建令牌
     * 通过jwt创建令牌
     *
     * @param params 参数个数
     * @return {@link String}
     */
    public static String createToken(Object params) {

        Map map = JSONObject.parseObject(JSON.toJSONString(params), Map.class);

        Map<String, Object> head = new HashMap<>();
        head.put("alg", "HS256");
        head.put("typ", "JWT");

        // 定义颁发时间
        Date iss = new Date();

        // 过期时间
        Calendar newTime = Calendar.getInstance();
        newTime.add(Calendar.MINUTE, 30);
        Date expire = newTime.getTime();

        String token = JWT.create()
                //指定头信息
                .withHeader(head)
                //载荷种的过期时间
                .withExpiresAt(expire)
                //颁发时间
                .withIssuedAt(iss)
                //颁发人
                .withIssuer("guilingcao")
                //自定义的载荷内容
                .withClaim("userInfo", map)
                // 签名
                .sign(Algorithm.HMAC256(SIGN));

        return token;
    }


    /**
     * 验证令牌:判断token是否合法
     *
     * @param token 令牌
     * @return boolean
     */
    public static boolean verifyToken(String token) {
        JWTVerifier build = JWT.require(Algorithm.HMAC256(SIGN)).build();
        try {
            DecodedJWT verify = build.verify(token);
            return true;
        } catch (Exception e) {
//            e.printStackTrace();
            log.error("token不合法。。。。");
            return false;
        }
    }


    /**
     * 解码jwt: 解析token种的内容
     *
     * @param token 令牌
     * @return {@link Map}<{@link String},{@link Object}>
     */
    public static Map<String, Object> decodeJWT(String token) {
        Map<String, Object> userInfo = JWT.decode(token).getClaim("userInfo").asMap();
        return userInfo;
    }

    public static void main(String[] args) {
        User user = new User();
        user.setId(1L);
        user.setEmail("2233434@qq.com");
        user.setPassword("123456");
        Map map = JSONObject.parseObject(JSON.toJSONString(user), Map.class);
        String token = createToken(user);
        System.out.println(token);

        Map<String, Object> map2
                = decodeJWT(token);
        System.out.println(map2);

        boolean is = verifyToken("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJndWlsaW5nY2FvIiwiZXhwIjoxNjY5MTcyMTY5LCJpYXQiOjE2NjkxNzAzNjl9.EKaGSBLpkDg2Pr7_mr_XOubkVdEFTYEHcgXoi4zeK20");
        System.out.println(is);
    }
}
